package com.finger.wx.assistant.util.xml;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 生成Node
public class NodeBuilder {
	private Node root = new Node();
	private XmlParser parser;
	private XmlFilter filter;

	// 提供合适的过滤器和解析器
	public NodeBuilder(XmlParser parser, XmlFilter filter) {
		this.parser = parser;
		this.filter = filter;
	}

	public Node getRoot(String... regex) {
		String str = null;
		if (regex.length == 0) {
			str = filter.filter();
		} else {
			str = filter.filter(regex);
		}
		buildNodeTree(str, root);
		return root;
	}

	// 设置节点类型
	private void buildNodeTitle(String str, Node n) {
		Pattern p = Pattern.compile("<.*?>");
		Matcher m = p.matcher(str);
		if (m.find()) {
			String temp = m.group();
			String s = temp.substring(1, temp.length() - 1).split(" ")[0];
			if (s.endsWith("/")) {
				n.setTitle(s.substring(0, s.length() - 1));
			} else {
				n.setTitle(s.split(" ")[0]);
			}
		}
	}

	// 设置节点属性集合
	private void buildNodeAttribute(String str, Node n) {
		Pattern p = Pattern.compile("<.*?>");
		Matcher m = p.matcher(str);
		if (m.find()) {
			String temp = m.group();
			String s = temp.substring(1, temp.length() - 1);
			// 匹配字符串
			p = Pattern.compile("(\\S*)=\"(.*?)\"");
			m = p.matcher(s);
			while (m.find()) {
				String key = m.group(1).trim();
				String value = m.group(2).trim();
				n.getAttribute().put(key, value);
			}
			// 匹配数字
			p = Pattern.compile("(\\S*)=(-?\\d+(\\.\\d+)?)");
			m = p.matcher(s);
			while (m.find()) {
				String key = m.group(1).trim();
				String value = m.group(2).trim();
				n.getAttribute().put(key, value);
			}
		}
	}

	// 设置节点内容,节点的内容是删除了所有子节点字符串以后剩下的部分
	private void buildNodeText(String str, Node n) {
		Pattern p = Pattern.compile("<.*?>(.*)</.*?>");
		Matcher m = p.matcher(str);
		List<String> childrenDocs = parser.parser(str);
		if (m.find()) {
			String temp = m.group(1);
			for (String s : childrenDocs) {
				temp = temp.replaceAll(s, "");
			}
			n.setText(temp.trim());
		}
	}

	// 通过递归生成完整节点树
	private void buildNodeTree(String str, Node n) {
		buildNodeTitle(str, n);
		buildNodeAttribute(str, n);
		buildNodeText(str, n);
		// 如果存在子节点则继续下面的操作
		if (!parser.parser(str).isEmpty()) {
			// 对每一个子节点都应该继续调用直到递归结束
			for (String temp : parser.parser(str)) {
				Node child = new Node();
				buildNodeTitle(temp, child);
				buildNodeAttribute(temp, child);
				buildNodeText(temp, child);
				n.getChildNode().add(child);
				buildNodeTree(temp, child);
			}
		}
	}
}